#ifndef DEFECTSTATISTICS_H
#define DEFECTSTATISTICS_H

#include <QVector>
#include <QObject>
#include <QVariantList>
#include "source/logger.h"
#include "ngtable.h"

class DefectStatistics : public QObject {
    Q_OBJECT
    Q_PROPERTY(int goodLabelsCount READ goodLabelsCount NOTIFY statisticsChanged)
    Q_PROPERTY(int defectLabelsCount READ defectLabelsCount NOTIFY statisticsChanged)
    Q_PROPERTY(QVariantMap defectCounts READ defectCounts NOTIFY statisticsChanged)

public:
    static DefectStatistics& instance() {
        static DefectStatistics instance;
        return instance;
    }
    QString upanPath = "/media/usb/";
    int goodLabelsCount() const { return m_goodLabelsCount; }
    int defectLabelsCount() const { return m_defectLabelsCount; }
    QVariantMap defectCounts() const { return m_defectCounts; }
    void exportDataToCSV(const QVector<QVector<int>>& data);
        //diaoyong
    void setData(const QVector<QVector<int>>& data) {
        m_data = data;
        updateStatistics();
    }

signals:
    void statisticsChanged();

private:
    DefectStatistics(QObject* parent = nullptr) : QObject(parent) {
        updateStatistics();
    }

    void updateStatistics() {
        m_goodLabelsCount = 0;
        m_defectLabelsCount = 0;
        m_defectCounts.clear();

        for (const auto& defects : m_data) {
            if (defects.isEmpty()) {
                ++m_goodLabelsCount;
            } else {
                ++m_defectLabelsCount;
                for (int defect : defects) {
                    std::vector<int> vec;
                    vec.push_back(defect);
                    QString key = NGTable::getInstance().parseNGListToDescription(vec);
                    if (!m_defectCounts.contains(key)) {
                        m_defectCounts[key] = 0;
                    }
                    m_defectCounts[key] = m_defectCounts[key].toInt() + 1;
                }
            }
        }

        LogDebug << "Good Labels Count:" << m_goodLabelsCount;
        LogDebug << "Defect Labels Count:" << m_defectLabelsCount;
        for (auto it = m_defectCounts.begin(); it != m_defectCounts.end(); ++it) {
            LogInfo << "Defect Type" << it.key() << "Count:" << it.value().toInt();
        }

        emit statisticsChanged();
    }

    QVector<QVector<int>> m_data;
    int m_goodLabelsCount = 0;
    int m_defectLabelsCount = 0;
    QVariantMap m_defectCounts;

    // 禁止拷贝构造和赋值
    DefectStatistics(const DefectStatistics&) = delete;
    DefectStatistics& operator=(const DefectStatistics&) = delete;
};

#endif // DEFECTSTATISTICS_H
